/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ericsson.nfc.signing.algorithm;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;

/**
 *
 * @author emarkki
 */
public class RsaSsaPkcs1V15SatsaVerifier implements SignatureVerifier {

    private static RsaSsaPkcs1V15SatsaVerifier instance;
    
    public static RsaSsaPkcs1V15SatsaVerifier getInstance() {
        if(instance == null) {
            instance = new RsaSsaPkcs1V15SatsaVerifier();
        }
        return instance;
    }
    
    public boolean verifySignature(byte[] signature, byte[] coveredBytes, PublicKey key) throws SignatureException {
        try {
//            System.out.println("SATSA");
            SubjectPublicKeyInfo pkInfo = key.getSubjectPublicKeyInfo();

            X509EncodedKeySpec pks = new X509EncodedKeySpec(pkInfo.getEncoded());
            KeyFactory kf = KeyFactory.getInstance("RSA");

            java.security.Signature sign = java.security.Signature.getInstance("SHA1withRSA");
            sign.initVerify(kf.generatePublic(pks));
            sign.update(coveredBytes, 0, coveredBytes.length);

            return sign.verify(signature);
        } catch (java.security.SignatureException ex) {
            throw new SignatureException(ex);
        } catch (InvalidKeyException ex) {
            throw new SignatureException(ex, "InvalidKeyException: " + ex.getMessage());
        } catch (InvalidKeySpecException ex) {
            throw new SignatureException(ex, "InvalidKeySpecException: " + ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("NoSuchAlgorithmException: " + ex.getMessage());
        } catch (IOException ex) {
            throw new SignatureException(ex, "IOException: " + ex.getMessage());
        }
    }

}
